
import React, { useState, useRef } from "react";
import { getCookie } from '@/utils'
import md5 from 'js-md5'
import styles from './login.module.scss'
import { checkValidateTimes, getLoginValidateImg, getTelCodeToken, sendLoginPanelIn, sendLoginValidateInfo } from "./api";
export function LoginPhone(props: { getUserInfo: (arg0: boolean) => void; loginType: string; }) {

    const { loginType, getUserInfo } = props

    const [phoneSendDisabled, setPhoneSendDisabled] = useState(false)

    const [phoneSendCountDownNum, setPhoneSendCountDownNum] = useState(0)

    const phoneNumRef = useRef<HTMLInputElement>(null)

    const phoneMsgNumRef = useRef<HTMLInputElement>(null)

    // 错误提示信息
    const [loginError, setLoginError] = useState('')
    /**
     * 手机登录刷新验证码图片
     */
    const clickValidataImg = () => {
        getLoginValidateImg()
    }

    /**
     *手机登录点击发送验证码
     *
     * @returns
     * @memberof LoginPanel
     */
    const clickValidataPhoneNum = () => {
        if (phoneSendDisabled) return;
        let phoneNum = phoneNumRef ? (phoneNumRef.current as HTMLInputElement).value : '';
        if (!(/^1[3456789]\d{9}$/.test(phoneNum))) {
            setLoginError('请输入正确的手机号')
            return false;
        } else {
            let now = new Date();
            let year = now.getFullYear();
            let month = String(now.getMonth() + 1).length > 1 ? String(now.getMonth() + 1) : `0${String(now.getMonth() + 1)}`;
            let day = String(now.getDate()).length > 1 ? String(now.getDate()) : `0${String(now.getDate())}`;
            let session_id = getCookie("IPSSESSION");
            let sms_key = md5(md5(`${year}-${month}-${day}_actionSendTelLoginCode_${session_id}`));

            getTelCodeToken(sms_key).then(data => {
                data.json().then(res => {
                    if (res.stat == 1) {
                        sendLoginValidateInfo({ phoneNum, token: res.data }).then(data => {
                            data.json().then(res => {
                                const { stat, msg = '' } = res;

                                if (stat == 1) {
                                    setPhoneSendDisabled(true);
                                    setLoginError('')
                                    setPhoneSendBtnTxt();
                                } else {
                                    setLoginError(msg)
                                    clickValidataImg();
                                    (window as any).callback = (res: { ret: number; ticket: string; randstr: string; }) => {
                                        if (res.ret == 0) {
                                            checkValidateTimes({ tel: phoneNum, ticket: res.ticket, rendstr: res.randstr }).then(data => {
                                                data.json().then(res => {
                                                    if (res.stat === 1) {
                                                        clickValidataPhoneNum();
                                                    }
                                                })
                                            })
                                        }
                                    }
                                    if ([2, -101].includes(res.stat)) {
                                        let checkBtn = document.createElement('button');
                                        checkBtn.id = "CaptchaEl";
                                        checkBtn.type = 'button';
                                        checkBtn.setAttribute('data-appid', "2032266202");
                                        checkBtn.setAttribute('data-cbfn', "callback");
                                        let captcha1 = new (window as any).Captcha(checkBtn);
                                        captcha1.show();
                                        return
                                    }
                                }
                            })
                        });
                    }
                });
            });
        }
    }

    /**
     *倒计时手机发送验证码按钮
     *
     * @memberof LoginPanel
     */
    const setPhoneSendBtnTxt = () => {
        let timeout = setTimeout(() => {
            let newNum = phoneSendCountDownNum - 1;
            setPhoneSendCountDownNum(newNum)
            if (newNum > 0) {
                setPhoneSendBtnTxt();
            } else {
                setPhoneSendDisabled(true);
                setPhoneSendCountDownNum(60)
                clickValidataImg();
            }
            clearTimeout(timeout);
        }, 1000)
    }

    /**
     *点击手机登录
     *
     * @memberof LoginPanel
     */
    const phoneLoginIn = () => {
        let phoneNum = phoneNumRef ? (phoneNumRef.current as HTMLInputElement).value : '';
        let phoneMsgNum = phoneMsgNumRef ? (phoneMsgNumRef.current as HTMLInputElement).value : '';
        if (!(/^1[3456789]\d{9}$/.test(phoneNum))) {
            setLoginError('请输入正确的手机号')
            return;
        }

        if (phoneMsgNum == '') {
            setLoginError('请输入正确的手机验证码')
            return;
        }
        sendLoginPanelIn({ phoneNum, phoneMsgNum }).then(data => {
            data.json().then(res => {
                const { stat = '', msg = '' } = res;
                if (stat == 1) {
                    setLoginError('')
                    localStorage.setItem("token", res.token);
                    getUserInfo(true)
                } else {
                    setLoginError(msg)
                }
            })
        });
    }
    return (
        <div className={styles.resPhoneLogin} style={{ zIndex: loginType == 'wechat' ? -9999 : 10 }}>
            <div className={styles.telLoginTitle}>
                <i className={`${styles.iconfont} ${styles.iconShouji}`}></i>
                <span>手机验证码登录</span>
            </div>
            <div className={styles.telLoginInputArea}>
                <input type="text" className={styles.telLoginNumber} placeholder="请输入手机号" ref={phoneNumRef} />
                <div className={styles.telLoginSendCode}>
                    <input type="text" className={styles.telLoginTelCode} placeholder="短信验证码" ref={phoneMsgNumRef} />
                    <a
                        className={phoneSendDisabled ? styles.submitDisabled : ''}
                        onClick={clickValidataPhoneNum}>
                        {phoneSendDisabled ? `重新发送（${phoneSendCountDownNum}）` : '发送验证码'}
                    </a>
                </div>
                <div className={styles.telLoginError} style={loginError != '' ? { opacity: 1 } : {}}>{loginError}</div>
                <a className={styles.telLoginSubmit} onClick={phoneLoginIn}>立即登录</a>
            </div>

        </div>
    )
}